package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.exception.checkItemException;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.mapper.CheckItemMapper;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class CheckItemServiceImpl implements CheckItemService {
    private final CheckItemMapper checkItemMapper;
    private final CheckGroupMapper checkGroupMapper;
    /**
     * 添加检查项
     * @param checkItem
     */
    @Override
    public void addInspectionItems(CheckItem checkItem) {
        checkItemMapper.addInspectionItems(checkItem);
    }
    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<CheckItem> page= checkItemMapper.checkItemQuery(queryPageBean);
        return new PageResult(page.getTotal(),page.getResult());
    }
    /**
     * 删除检查项
     * @param id
     */
    @Transactional
    @Override
    public void deleteInspectionItems(Long id) {
        List<Long> checkGroupIds =checkItemMapper.findCheckGroupIdByCheckItemIds(id);
        if (!checkGroupIds.isEmpty()||checkGroupIds.size()>0){
            throw  new checkItemException(MessageConstant.DELETE_CHECKITEM_NOT_NULL);
        }
            checkItemMapper.delete(id);
    }
    /**
     * 修改检查项
     * @param checkItem
     */
    @Override
    public void updateInspectionItems(CheckItem checkItem) {
       checkItemMapper.updata(checkItem);

    }

    @Override
    public List<CheckItem> findByAllInspectionItems() {
        return checkItemMapper.findByAllCheckItems();
    }

    @Override
    public List<CheckItem> findByIdInspectionItems(Long id) {
        List<CheckItem> byIdCheckItems = checkItemMapper.findByIdCheckItems(id);
        if (byIdCheckItems==null || byIdCheckItems.isEmpty()){
            throw new checkItemException(MessageConstant.QUERY_CHECKITEM_FAIL);
        }
        return byIdCheckItems;
    }

    @Override
    public List<Long> findCheckItemIdsByCheckGroupId(Long checkgroupId) {
        List<Long> ids = checkItemMapper.findCheckItemIdsByCheckGroupId(checkgroupId);
        if (ids==null || ids.isEmpty()){
            throw new checkItemException(MessageConstant.QUERY_CHECKITEM_FAIL);
        }
        return ids;
    }
}
